package com.example.cm_player.activity

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.os.Handler
import android.os.Looper
import com.example.cm_base.BaseViewModel
import com.example.cm_player.model.SongInfo
import com.example.cm_player.model.PlayMode
import com.example.cm_player.manager.PlayerStateManager
import com.example.cm_player.service.PlayerService
import com.example.cm_utils.ContextHelper

/**
 * 播放器ViewModel，管理播放状态和UI交互
 */
class PlayerViewModel : BaseViewModel() {
    private var playerService: PlayerService? = null
    private var bound = false
    private val handler = Handler(Looper.getMainLooper())
    private val progressUpdateRunnable = object : Runnable {
        override fun run() {
            updatePlaybackProgress()
            handler.postDelayed(this, 1000)
        }
    }

    // 服务连接
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as PlayerService.PlayerBinder
            playerService = binder.getService()
            bound = true

            // 启动进度更新
            startProgressUpdates()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            playerService = null
            bound = false

            // 停止进度更新
            stopProgressUpdates()
        }
    }

    /**
     * 绑定播放服务
     */
    fun bindPlayerService() {
        ContextHelper.context.get()?.let {
            val intent = Intent(it, PlayerService::class.java)
            it.bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    fun startService(){
        ContextHelper.context.get()?.let {
            val intent = Intent(it, PlayerService::class.java)
            it.startService(intent)
        }
    }

    /**
     * 解绑播放服务
     */
    fun unbindPlayerService() {
        stopProgressUpdates()
        if (bound) {
            ContextHelper.context.get()?.unbindService(connection)
            bound = false
        }
    }

    fun setPlayMode(playMode: PlayMode) {
        playerService?.setPlayMode(playMode)
    }

    fun removeFromPlaylist(songInfo: SongInfo){
        playerService?.removeFromPlaylist(songInfo)
    }

    /**
     * 播放歌曲
     */
    fun playSong(songInfo: SongInfo) {
        startService()
        playerService?.play(songInfo)
    }


     fun previousMusic() {
         playerService?.previousMusic()
    }

     fun nextMusic() {
         playerService?.nextMusic()
    }

    /**
     * 暂停/继续播放
     */

    fun pause(){
        playerService?.pause()
    }

    /**
     * 停止播放
     */
    fun stopPlayback() {
        playerService?.stop()
    }

    /**
     * 跳转到指定位置
     * @param percent 进度百分比(0-100)
     */
    fun seekTo(percent: Float) {
        val duration = PlayerStateManager.duration.value ?: return
        val targetPosition = (percent * duration / 100).toLong()
        playerService?.seekTo(targetPosition)
    }

    /**
     * 启动进度更新
     */
    private fun startProgressUpdates() {
        handler.post(progressUpdateRunnable)
    }

    /**
     * 停止进度更新
     */
    private fun stopProgressUpdates() {
        handler.removeCallbacks(progressUpdateRunnable)
    }

    /**
     * 更新播放进度
     */
    private fun updatePlaybackProgress() {
        playerService?.playerManager?.let { manager ->
            val currentPos = manager.getCurrentPosition()
            val totalDuration = manager.getDuration()

            if (totalDuration > 0) {
                // 更新原始的进度值(毫秒)而不是百分比
                PlayerStateManager.updateProgress(currentPos)
                
                // 确保总时长也正确设置
                if (PlayerStateManager.duration.value != totalDuration) {
                    PlayerStateManager.updateDuration(totalDuration)
                }
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        unbindPlayerService()
    }

    fun start() {
        playerService?.resume()
    }
}